package com.pernix.authen.network;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import com.pernix.log.ConsoleLogging;
import com.pernix.log.ILog;

public class AuthenServer {
	private SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm:ss");
	private ILog Logger;
	private Thread serverThread;
	private ServerSocket serverSocket;
	private Socket socket;
	private int port;

	public AuthenServer(ILog logger) {
		this(logger, 1812);
	}

	public AuthenServer(ILog logger, int port) {
		this.Logger = logger;
		this.port = port;
		serverThread = new Thread(new ServerRunnable());
	}

	public void start() {
		serverThread.start();
	}

	public void stop() {
		serverThread.interrupt();
		try {
			serverSocket.close();
			if (socket != null) {
				socket.close();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Logger.Debug("Authen Server stop..");
	}

	private class ServerRunnable implements Runnable {
		@Override
		public void run() {
			try {
				serverSocket = new ServerSocket(port);
				Logger.Debug(String.format(
						"Authen Server start listen on port: %s", port));
				socket = null;
				while (!Thread.currentThread().isInterrupted()) {
					try {
						socket = serverSocket.accept();
					} catch (IOException e1) {
						System.out.println("serverSocket closed");
					}
					if (socket != null) {
						Thread clientThead = new Thread(new AuthenClientRunnable(Logger, socket));
						clientThead.start();
						//clientThead.interrupt();
					}
				}
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				System.out.println("Socket is closed");
				//e1.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		AuthenServer server = new AuthenServer(new ConsoleLogging());
		server.start();
		try {
			Thread.sleep(10000);
			//server.stop();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("main end.");
	}
}
